package com.example.utils;

import com.example.pojo.utils.SendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送工具类
 *
 * @author ding
 * @since 2024/7/15
 */
@Slf4j
@Component
public class SendMessageUtils {

    @Autowired
    private JavaMailSender javaMailSender;

    static String from = "207409830@qq.com";

    //发送普通邮件
    public void sendMessage(SendMessage sendMessage) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from + "(智慧工程客服)");
        mailMessage.setTo(sendMessage.getTo());
        mailMessage.setSubject(sendMessage.getSubject());
        mailMessage.setText(sendMessage.getContent());

        javaMailSender.send(mailMessage);
        log.info("邮件发送完毕");
    }

    //发送html邮件
    public void sendHTMLMessage(SendMessage sendMessage) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        try {
            helper.setFrom(from + "(智慧工程客服)");
            helper.setTo(sendMessage.getTo());
            helper.setText(sendMessage.getTo());
            helper.setSubject(sendMessage.getSubject());
            helper.setText(sendMessage.getContent(), true); //正文支持html解析

            javaMailSender.send(mimeMessage);
            log.info("含有下载链接的邮件已发送完成.....");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
